//
//  LTUserAccountViewModel.swift
//  微博08
//
//  Created by 123 on 16/3/4.
//  Copyright © 2016年 Tsr. All rights reserved.
//

import UIKit

class LTUserAccountViewModel: NSObject {
    
    // 单例
    static let sharedInstance: LTUserAccountViewModel = LTUserAccountViewModel()
    
    // 用户账号,通过单例可以全局访问
    var userAccount: LTUserAccount?
    
    // 3.1调用LTUserAccountViewModel的方法去加载请求
    func loadAccessToken(code: String) {
        // 3.2使用CZNetworkTool发起请求获取AccessToken,并且准备闭包
        LTNetworkTools.sharedInstance.loadAccessToken(code) { (response, error) -> () in
            // 3.7判断请求是否失败
            if response == nil || error != nil {
                print("access token 请求失败: \(error)")
                return
            }
            
            // 获取access token
            print("access token 请求成功: \(response)")
            
            // 3.8字典转模型,并赋值给属性
            self.userAccount = LTUserAccount(dict: response!)
            
            // 3.9将模型保存到沙盒中
            self.saveUserAccount()
        }
    }
    
    // 将对象保存到沙盒
    func saveUserAccount() {
        if userAccount != nil {
            
           let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/Account.plist")
            print("userAccount: \(accountPath)")
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
        }
    }

}
